<template>
  <div class="app-container">
    <el-form ref="invoiceFormRef" v-loading="loading" :model="form" :disabled="routeParams.type === 'view'"
      :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item v-if="routeParams.contractType === 'sale'" label="销售合同号" prop="saleContractNum">
            <sale-contract-select v-model:form="form" />
          </el-form-item>
          <el-form-item v-else label="采购合同号" prop="purchaseContractNum">
            <purchase-contract-select v-model:form="form" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input disabled v-model="form.projectName" placeholder="根据合同号带出" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运输路段" prop="transportSection">
            <el-select v-model="form.transportSection" placeholder="根据合同号带出" disabled>
              <el-option v-for="dict in transport_section" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="routeParams.contractType === 'sale'" label="客户名称" prop="customerName">
            <el-input disabled v-model="form.customerName" placeholder="根据合同号带出" />
          </el-form-item>
          <el-form-item v-else label="供应商名称" prop="supplierName">
            <el-input disabled v-model="form.supplierName" placeholder="根据合同号带出" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本币价税合计" prop="localTotalAmount">
            <el-input disabled style="width: 100%;" :value="formatAmount(form.localTotalAmount)"
              placeholder="根据合同号带出" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" maxlength="1000" v-model="form.remark" />
      </el-form-item>
    </el-form>
    <div class="button-group" v-if="routeParams.type !== 'view'">
      <el-button type="primary" @click="addRow" class="add-button">添加</el-button>
      <el-button type="danger" @click="removeRows" class="delete-button">删行</el-button>
    </div>
    <div style="margin-bottom: 30px;">
      <el-table height="400" :data="form.invoiceList" border @selection-change="handleSelectionChange"
        style="width: 100%; margin: 10px 0;">
        <!-- 多选列，仅编辑模式显示 -->
        <el-table-column type="selection" width="55" v-if="routeParams.type !== 'view'"></el-table-column>

        <!-- 发票号列 -->
        <el-table-column :label="routeParams.contractType === 'sale' ? '销售发票号' : '采购发票号'" align="center" width="180">
          <template #default="scope">
            <!-- 浏览模式 -->
            <span v-if="routeParams.type === 'view'">
              <template v-if="routeParams.contractType === 'sale'">
                {{ scope.row.saleInvoiceNum }}
              </template>
              <template v-else-if="routeParams.contractType === 'purchase'">
                {{ scope.row.purchaseInvoiceNum }}
              </template>
            </span>

            <!-- 编辑模式 -->
            <el-input v-else-if="routeParams.contractType === 'sale'" v-model="scope.row.saleInvoiceNum"
              placeholder="请输入销售发票号" />
            <el-input v-else v-model="scope.row.purchaseInvoiceNum" placeholder="请输入采购发票号" />
          </template>
        </el-table-column>


        <!-- 发票入账日期 -->
        <el-table-column label="发票入账日期" align="center" width="180">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">{{ formatDate(scope.row.recordDate) }}</span>
            <el-date-picker v-else style="width: 100%;" v-model="scope.row.recordDate" type="date"
              value-format="YYYY-MM-DD" placeholder="选择日期" />
          </template>
        </el-table-column>

        <!-- 相关凭证号 -->
        <el-table-column label="相关凭证号" align="center" width="180">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">{{ scope.row.voucherNum }}</span>
            <el-input v-else v-model="scope.row.voucherNum" placeholder="请输入相关凭证号" style="width: 100%;" />
          </template>
        </el-table-column>
         <!-- 原币价税合计 -->
        <el-table-column label="原币价税合计" align="center" width="200">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">{{ formatAmount(scope.row.originalTotalAmount) }}</span>
            <el-input-number v-else v-model="scope.row.originalTotalAmount" :precision="2" placeholder="请输入原币价税合计"
              style="width: 100%;" />
          </template>
        </el-table-column>
        <!-- 原币无税金额 -->
        <el-table-column label="原币无税金额" align="center" width="200">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">{{ formatAmount(scope.row.originalAmount) }}</span>
            <el-input-number v-else v-model="scope.row.originalAmount" :precision="2" placeholder="请输入原币无税金额"
              style="width: 100%;" />
          </template>
        </el-table-column>
        <!-- 原币税额 -->
        <el-table-column label="原币税额" align="center" width="200">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">{{ formatAmount(scope.row.originalTaxedAmount) }}</span>
            <el-input-number v-else v-model="scope.row.originalTaxedAmount" disabled :precision="2" placeholder="请输入原币税额"
              style="width: 100%;" />
          </template>
        </el-table-column>
        <!-- 币种 -->
        <el-table-column label="币种" align="center" width="200">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">
              {{bas_currency.find(item => item.value == scope.row.currency)?.label || ''}}
            </span>
            <el-select v-else v-model="scope.row.currency" placeholder="请选择币种" style="width: 100%;">
              <el-option v-for="dict in bas_currency" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)" />
            </el-select>
          </template>
        </el-table-column>

        <!-- 汇率 -->
        <el-table-column label="汇率" align="center" width="200">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">{{ Number(scope.row.exchangeRate || 0).toFixed(6) }}</span>
            <el-input-number v-else v-model="scope.row.exchangeRate" :disabled="scope.row.currency === 4" :precision="6" placeholder="请输入汇率"
              style="width: 100%;" />
          </template>
        </el-table-column>
        <!-- 本币价税合计 -->
        <el-table-column label="本币价税合计" align="center" width="200">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">{{ formatAmount(scope.row.localTotalAmount) }}</span>
            <el-input-number v-else v-model="scope.row.localTotalAmount" :precision="2" disabled placeholder="根据汇率自动计算"
              style="width: 100%;" />
          </template>
        </el-table-column>
        <!-- 本币无税金额 -->
        <el-table-column label="本币无税金额" align="center" width="200">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">{{ formatAmount(scope.row.localAmount) }}</span>
            <el-input-number v-else v-model="scope.row.localAmount" :precision="2" disabled placeholder="根据汇率自动计算"
              style="width: 100%;" />
          </template>
        </el-table-column>
        <!-- 本币税额 -->
        <el-table-column label="本币税额" align="center" width="200">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">{{ formatAmount(scope.row.localTaxedAmount) }}</span>
            <el-input-number v-else v-model="scope.row.localTaxedAmount" :precision="2" disabled placeholder="根据汇率自动计算"
              style="width: 100%;" />
          </template>
        </el-table-column>
        <!-- 备注 -->
        <el-table-column label="备注" align="center" width="200">
          <template #default="scope">
            <span v-if="routeParams.type === 'view'">{{ scope.row.remark }}</span>
            <el-input v-else v-model="scope.row.remark" placeholder="请输入备注" style="width: 100%;" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-row class="buttonBox">
      <el-button type="primary" @click="handleSave" v-if="routeParams.type === 'add' || routeParams.type === 'update'"
        :disabled="saveDisable">保存</el-button>
      <el-button @click="goBack">返回</el-button>
    </el-row>
  </div>

</template>
<script setup name="contractEdit" lang="ts">
import { getSaleInvoice, addSaleInvoice, updateSaleInvoice } from '@/api/finance/saleInvoice';
import { getPurchaseInvoice, addPurchaseInvoice, updatePurchaseInvoice } from '@/api/finance/purchaseInvoice';
import { InvoiceForm, InvoiceItem } from '@/api/finance/types';
const loading = ref(false);
const saveDisable = ref(false)
const selectedRows = ref<InvoiceItem[]>([])
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const routeParams = ref<Record<string, any>>({});
const { transport_section, bas_currency } = toRefs<any>(proxy?.useDict('transport_section', 'bas_currency'));

const initFormData: InvoiceForm = {
  id: undefined,
  saleContractId: undefined,
  saleContractNum: undefined,
  purchaseContractId: undefined,
  purchaseContractNum: undefined,
  projectName: undefined,
  transportSection: undefined,
  customerId: undefined,
  supplierId: undefined,
  localTotalAmount: undefined,
  remark: undefined,
  invoiceList: [],
}
const data = reactive({
  form: initFormData,
  rules: {
    saleContractNum: [
      { required: true, message: "销售合同号不能为空", trigger: "change" }
    ],
    purchaseContractNum: [
      { required: true, message: "采购合同号不能为空", trigger: "change" }
    ]
  }
})



const { form, rules } = toRefs(data);
const addRow = () => {
  form.value.invoiceList.push({
    id: '',
    saleInvoiceId: undefined,
    purchaseInvoiceId: undefined,
    recordDate: undefined,
    saleInvoiceNum: undefined,
    purchaseInvoiceNum: undefined,
    voucherNum: undefined,
    originalTotalAmount: undefined,
    originalAmount: undefined,
    originalTaxedAmount: undefined,
    localTotalAmount: undefined,
    localAmount: undefined,
    localTaxedAmount: undefined,
    remark: undefined,
    currency: 4,
    exchangeRate: 1,
  })
}
watch(
  () => form.value.invoiceList,
  (newList) => {
    newList.forEach((row) => {
      const originalAmount = Number(row.originalAmount) || 0;
      const originalTotalAmount = Number(row.originalTotalAmount) || 0;
      const exchangeRate = Number(row.exchangeRate) || 0;

      // 原币税额
      row.originalTaxedAmount = Number((originalTotalAmount - originalAmount).toFixed(2));

      // 本币金额计算
      row.localAmount = Number((originalAmount * exchangeRate).toFixed(2));
      row.localTaxedAmount = Number((row.originalTaxedAmount * exchangeRate).toFixed(2));
      row.localTotalAmount = Number((originalTotalAmount * exchangeRate).toFixed(2));
    });
  },
  { deep: true } // 必须开启深度监听
);
watch(
  () => form.value.invoiceList.map(r => r.currency),
  (currencies) => {
    currencies.forEach((cur, index) => {
      if (cur === 4) {
        form.value.invoiceList[index].exchangeRate = 1;
      } else {
        form.value.invoiceList[index].exchangeRate = undefined;
      }
    });
  },
  { deep: true }
);
const removeRows = () => {
  form.value.invoiceList = form.value.invoiceList.filter(item => !selectedRows.value.includes(item));
}
const handleSelectionChange = (val: InvoiceItem[]) => {
  selectedRows.value = val;
};
const handleSave = async () => {
  if (saveDisable.value) return;

  const formRef = proxy.$refs["invoiceFormRef"];
  if (!formRef) return;

  saveDisable.value = true;

  try {
    const valid = await formRef.validate();
    if (!valid) return;

    // 验证金额逻辑
    if (!validateInvoiceList()) return;
    if (routeParams.value.contractType === 'sale') {
      form.value.saleInvoiceList = [...form.value.invoiceList];
      form.value.purchaseInvoiceList = [];
    } else {
      form.value.purchaseInvoiceList = [...form.value.invoiceList];
      form.value.saleInvoiceList = [];
    }

    if (routeParams.value.type === 'add') {
      await saveInvoice(form.value, routeParams.value.contractType === 'sale', true);
      proxy?.$modal.msgSuccess("保存成功");
    } else if (routeParams.value.type === 'update') {
      await saveInvoice(form.value, routeParams.value.contractType === 'sale', false);
      proxy?.$modal.msgSuccess("修改成功");
    }

    proxy.$tab.closePage(proxy.$route);
    proxy.$router.go(-1);
  } finally {
    saveDisable.value = false;
  }
};
const saveInvoice = async (data: any, isSale: boolean, isAdd: boolean) => {
  if (isAdd) {
    return isSale ? addSaleInvoice(data) : addPurchaseInvoice(data);
  } else {
    return isSale ? updateSaleInvoice(data) : updatePurchaseInvoice(data);
  }
};
const getInfo = async () => {
  const contractType = routeParams.value.contractType;

  if (contractType === 'sale') {
    const res = await getSaleInvoice(routeParams.value.id);
    form.value = {
      ...res.data,
      invoiceList: res.data.saleInvoiceList || [],
    };
  } else if (contractType === 'purchase') {
    const res = await getPurchaseInvoice(routeParams.value.id);
    form.value = {
      ...res.data,
      invoiceList: res.data.purchaseInvoiceList || [],
    };
  }
};
const validateInvoiceList = (): boolean => {
  if (!form.value.invoiceList || form.value.invoiceList.length === 0) {
    ElMessage.warning("请至少添加一条发票数据");
    return false;
  }

  for (let i = 0; i < form.value.invoiceList.length; i++) {
    const item = form.value.invoiceList[i];

    // 发票号
    if (routeParams.value.contractType === 'sale' && !item.saleInvoiceNum) {
      ElMessage.warning(`第 ${i + 1} 行销售发票号不能为空`);
      return false;
    }
    if (routeParams.value.contractType === 'purchase' && !item.purchaseInvoiceNum) {
      ElMessage.warning(`第 ${i + 1} 行采购发票号不能为空`);
      return false;
    }

    // 发票入账日期
    if (!item.recordDate) {
      ElMessage.warning(`第 ${i + 1} 行发票入账日期不能为空`);
      return false;
    }

    // 相关凭证号
    if (!item.voucherNum) {
      ElMessage.warning(`第 ${i + 1} 行相关凭证号不能为空`);
      return false;
    }

    // 原币金额字段
    if (item.originalAmount === null || item.originalAmount === undefined) {
      ElMessage.warning(`第 ${i + 1} 行原币无税金额不能为空`);
      return false;
    }
    if (item.originalTaxedAmount === null || item.originalTaxedAmount === undefined) {
      ElMessage.warning(`第 ${i + 1} 行原币税额不能为空`);
      return false;
    }
    if (item.originalTotalAmount === null || item.originalTotalAmount === undefined) {
      ElMessage.warning(`第 ${i + 1} 行原币价税合计不能为空`);
      return false;
    }

    // 币种
    if (!item.currency) {
      ElMessage.warning(`第 ${i + 1} 行币种不能为空`);
      return false;
    }

    // 汇率
    if (item.exchangeRate === null || item.exchangeRate === undefined) {
      ElMessage.warning(`第 ${i + 1} 行汇率不能为空`);
      return false;
    }

    // 本币金额字段
    if (item.localAmount === null || item.localAmount === undefined) {
      ElMessage.warning(`第 ${i + 1} 行本币无税金额不能为空`);
      return false;
    }
    if (item.localTaxedAmount === null || item.localTaxedAmount === undefined) {
      ElMessage.warning(`第 ${i + 1} 行本币税额不能为空`);
      return false;
    }
    if (item.localTotalAmount === null || item.localTotalAmount === undefined) {
      ElMessage.warning(`第 ${i + 1} 行本币价税合计不能为空`);
      return false;
    }

    // 金额加总校验
    const originalAmount = Number(item.originalAmount || 0);
    const originalTaxed = Number(item.originalTaxedAmount || 0);
    const originalTotal = Number(item.originalTotalAmount || 0);

    const localAmount = Number(item.localAmount || 0);
    const localTaxed = Number(item.localTaxedAmount || 0);
    const localTotal = Number(item.localTotalAmount || 0);

    if (originalTotal - originalAmount !== originalTaxed) {
      ElMessage.warning(`第 ${i + 1} 行：原币价税合计 - 无税金额 必须等于税额`);
      return false;
    }

    if (localTotal - localAmount !== localTaxed) {
      ElMessage.warning(`第 ${i + 1} 行：本币价税合计 - 无税金额 必须等于税额`);
      return false;
    }
  }

  return true;
};

const formatDate = (date: string | Date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = d.getMonth() + 1;
  const day = d.getDate();
  return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
};

const formatAmount = (value) => {
  if (value === null || value === undefined || isNaN(Number(value))) {
    return '';
  }
  return Number(value).toFixed(2);
}

const goBack = () => {
  const from = proxy.$route.query.from;
  if (from) {
    proxy.$router.push(from);
  } else {
    proxy.$router.back();
  }
}
onMounted(async () => {
  loading.value = true
  routeParams.value = proxy.$route.query
  if (routeParams.value.type === 'update' || routeParams.value.type === 'view') {
    await getInfo();
  }
  loading.value = false
})
</script>

<style scoped>
.buttonBox {
  bottom: 20px;
  left: 40%;
}
</style>
